# -*- coding: utf_8 -*-
# @Time : 2021/8/10 0010 16:36
# @Author : lyw
# @Remark : 数据源view
import logging

from mxsoftpy import View
from server.common.IOTManager.Janitor.data_origin import (DataOriginServer, ADDDataOrigin, EchoOrigin,
                                                          SelectDataOriginServer, GetDataOriginServer,
                                                          GetConfigFieldServer)
from utils.classes.custom_exception import VerifyError
from utils.public.params_method import process
from index import _


class DataOriginModel(View):
    @staticmethod
    def get():
        """获取产品模板"""
        return "ok", DataOriginServer().get_data_origin_model()


class DataOrigin(View):

    def post(self):
        """新增数据源"""
        param = self.request.POST
        if not param:
            return "参数不存在..."
        return "ok", ADDDataOrigin(param["type_id"]).add_data_origin(**param)

    def get(self):
        """回显"""
        return "ok", EchoOrigin().echo_origin(**self.request.GET)


class UpdateOrigin(View):
    def post(self):
        """修改数据源"""
        param = self.request.POST
        if not param:
            return "参数不存在..."
        if param.get("type_id") not in ("1", "2", "3"):
            return "请传入正确的type_id参数..."
        return "ok", ADDDataOrigin(param["type_id"]).update_data_origin(**param)


class MultipleOpen(View):

    def get(self):
        """ 展示数据 """
        param = self.request.GET

        param['search'] = process(param, 'search', '')  # 默认 无搜索内容
        param['state'] = int(process(param, 'state', 2, ['0', '1', '2']))  # 默认 为全部状态 0为关闭，1为开启，2为全部
        param['pageindex'] = int(process(param, 'pageindex', 1))  # 默认 为第一页
        param['pagesize'] = int(process(param, 'pagesize', 20))  # 默认20，每页显示数量
        try:
            """res 即 response 返回结果"""
            res = GetDataOriginServer().get_origin_data(**param)
        except TypeError as e:
            logging.error(e)
            raise VerifyError(_("您的参数格式不对，请查看接口文档"))
        return 'ok', res

    def post(self):
        """ 批量修改状态 """
        param = self.request.POST if len(self.request.POST) == 2 else self.request.GET
        if not param.get("origin_id") or not param.get('state') or param.get('state') not in ("0", "1", "2"):
            return "origin_id或state参数不存在或者格式不正确..."
        try:
            """res 即 response 返回结果"""
            res = SelectDataOriginServer().update_state(**param)
        except TypeError as e:
            logging.error(e)
            raise VerifyError(_("您的参数格式不对，请查看接口文档"))
        return "ok", res


class GetConfigField(View):

    def get(self):
        """获取配置字段"""
        return _('查询成功'), GetConfigFieldServer().get_field(**self.request.GET)
